
#include "DirInit.h"

/* clean temporary structures and do exit(ret) */
void DirInit::cleanup(int ret) {
    if (currDir != NULL) {
	free(currDir);
	currDir = NULL;
    }
    if (tagfsDir != NULL) {
	free(tagfsDir);
	tagfsDir = NULL;
    }
    if (mountDir != NULL) {
	free(mountDir);
	mountDir = NULL;
    }
    if (repoDir != NULL) {
	free(repoDir);
	repoDir = NULL;
    }

    exit(ret);
}

/* output error message m to stream str */
void DirInit::descError(FILE* str, const char* m) {
    fprintf(str, m);
    fprintf(str, strerror(errno));
    fprintf(str, "\n");
}

/* allocate memory and check for errors */
void* DirInit::doMalloc(int size) {
    void* ret;

    ret = malloc(size);
    if (ret == NULL) {
	descError(INFOS, "Error in malloc\n");
	cleanup(1);
    }
    return ret;
}

/* checks for existence of a directory and creates it; 0 on success */ 
int DirInit::enterDir(char* dir) {
    struct stat bufStat;

    /* exists? */
    if (stat(dir, &bufStat) != 0) {
	if (errno != ENOENT) {
	    descError(INFOS, "Problem with filesystem. Exiting.\n");
	    cleanup(1);
	}
	if (mkdir(dir, 0755) != 0) {
	    fprintf(INFOS, "Error creating directory:\n%s\n", dir);
	    descError(INFOS, "");
	    cleanup(1);
	}
    }
    /* dir? */
    else { 
	if (!S_ISDIR(bufStat.st_mode)) {
	    fprintf(INFOS, "Error creating directory:\n%s\n", dir); 
	    fprintf(INFOS, "Normal file existing already.\n");
	    cleanup(1);
	}
    }
    return 0;
}

void DirInit::initDirs(int argc, char** argv) {
    struct	    stat bufStat;
    char*	    homeDir = NULL;
    unsigned int    mountDirSize = 0;

    /* count params */
    if (argc < 3) {
    	fprintf(INFOS, "Program must be run with two arguments:\n");
	fprintf(INFOS, " ./tag-fs repository mount-point\n");
	cleanup(1);
    }
    /* get current dir */
    currDir = getcwd(currDir, 0);
    if (currDir == NULL) {
	descError(INFOS, "Cannot determine current directory.\n");
	cleanup(1);
    }
    /* convert mountpoint to absolute */
    mountDirSize = strlen(argv[2]) + 2 + strlen(currDir);
    mountDir = (char*)doMalloc(mountDirSize);
    if (rel2abs(argv[2], currDir, mountDir, mountDirSize) == NULL) {
	fprintf(INFOS, "Cannot find absolute path to mountpoint. Exiting.\n");
	cleanup(1);
    }
    /* check for mountpoint existence */
    if (stat(argv[2], &bufStat) == -1) {
	if (errno == ENOENT)
	    fprintf(INFOS, "Mountpoint not existing. Try again...\n");
    	else
	    descError(INFOS, "Problem with filesystem. Exiting.\n");
	cleanup(1);
    }
    /* check for mountpoint being a dir */
    if (!S_ISDIR(bufStat.st_mode)) {
	fprintf(INFOS, "Mountpoint is not a directory. Try again...\n");
	cleanup(1);
    }

    /* find or create .tagfs dir */
    homeDir = getenv("HOME");
    if (homeDir == NULL) {
	fprintf(INFOS, "Error reading $HOME. No home directory?\n");
	exit(1);
    }
    tagfsDir = (char*)doMalloc(strlen(homeDir) + 2 + strlen(tagfsDirName));
    strcpy(tagfsDir, homeDir);
    strcat(tagfsDir, "/");
    strcat(tagfsDir, tagfsDirName);
    /* check for existence and create */
    enterDir(tagfsDir);

    /* find or create .tagfs/repo */
    repoDir = (char*)doMalloc(strlen(tagfsDir) + 2 + strlen(argv[1]));
    strcpy(repoDir, tagfsDir);
    strcat(repoDir, "/");
    strcat(repoDir, argv[1]);
    /* check for existence and create */
    enterDir(repoDir);

    /* find or create .tagfs/repo/Files */
    filesDir = (char*)doMalloc(strlen(repoDir) + 2 + strlen(filesDirName));
    strcpy(filesDir, repoDir);
    strcat(filesDir, "/");
    strcat(filesDir, filesDirName);
    /* check for existence and create */
    enterDir(filesDir);
    
    /* checking options */
    this->build = 0;
    this->verbose = 0;

    if (argc > 3){
    	for (int i = 3; i < argc; i++){
    		if (string(argv[i]) == "-d")
    			this->verbose = 1;
    		if ((string(argv[i]) == "-b") && (i + 1 < argc)){
    			this->build = 1;
    			this->build_dir = argv[i + 1];
    			i++;
			}
		}
	};

}

char* DirInit::getMountDir() {
    return mountDir;
}

char* DirInit::getRepoDir() {
    return repoDir;
}

int DirInit :: shouldBuild(){
	return this->build;
};

string DirInit :: getBuildDir(){
	return this->build_dir;
};

DirInit::DirInit() {
	tagfsDir = NULL;
	mountDir = NULL;
	repoDir = NULL;
	currDir = NULL;
} 

/*
 * Copyright (c) 1997 Shigio Yamaguchi. All rights reserved.
 * Copyright (c) 1999 Tama Communications Corporation. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

char* DirInit :: rel2abs(const char *path, const char *base,
	char *result, const size_t size)
{
	const char *pp, *bp;
	/*
	 * endp points the last position which is safe in the result buffer.
	 */
	const char *endp = result + size - 1;
	char *rp;
	unsigned int length;

	if (*path == '/') {
		if (strlen(path) >= size)
			goto erange;
		strcpy(result, path);
		goto finish;
	} else if (*base != '/' || !size) {
		errno = EINVAL;
		return (NULL);
	} else if (size == 1)
		goto erange;
	length = strlen(base);

	if (!strcmp(path, ".") || !strcmp(path, "./")) {
		if (length >= size)
			goto erange;
		strcpy(result, base);
		/*
		 * rp points the last char.
		 */
		rp = result + length - 1;
		/*
		 * remove the last '/'.
		 */
		if (*rp == '/') {
			if (length > 1)
				*rp = 0;
		} else
			rp++;
		/* rp point NULL char */
		if (*++path == '/') {
			/*
			 * Append '/' to the tail of path name.
			 */
			*rp++ = '/';
			if (rp > endp)
				goto erange;
			*rp = 0;
		}
		goto finish;
	}
	bp = base + length;
	if (*(bp - 1) == '/')
		--bp;
	/*
	 * up to root.
	 */
	for (pp = path; *pp && *pp == '.'; ) {
		if (!strncmp(pp, "../", 3)) {
			pp += 3;
			while (bp > base && *--bp != '/')
				;
		} else if (!strncmp(pp, "./", 2)) {
			pp += 2;
		} else if (!strncmp(pp, "..\0", 3)) {
			pp += 2;
			while (bp > base && *--bp != '/')
				;
		} else
			break;
	}
	/*
	 * down to leaf.
	 */
	length = bp - base;
	if (length >= size)
		goto erange;
	strncpy(result, base, length);
	rp = result + length;
	if (*pp || *(pp - 1) == '/' || length == 0)
		*rp++ = '/';
	if (rp + strlen(pp) > endp) {
		goto erange;
	}
	strcpy(rp, pp);
finish:
	return result;
erange:
	errno = ERANGE;
	return (NULL);
}
